package lc20240516;

import java.util.ArrayDeque;
import java.util.Deque;

public class Demo3 {
    public static void main(String[] args) {
        String s="(1+(4+5+2)-3)+(6+8)";
        System.out.println(calculate(s));

    }

    public static int calculate(String s) {
        Deque<Integer> nums = new ArrayDeque<>();
        Deque<Character> ops = new ArrayDeque<>();

        int num = 0;
        int sign=1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            }else if (c=='+'){
                nums.push(num*sign);
                num=0;
                sign=1;
            } else if (c=='-') {
                nums.push(sign*num);
                num=0;
                sign=-1;
            }else if (c=='('){
                ops.push((char)sign);
                sign=1;
            } else if (c==')') {
                nums.push(num*sign);
                num=0;
                int sum=0;
                while (!nums.isEmpty()&&nums.peek()!=null){
                    sum+=nums.pop();
                }
                if (!ops.isEmpty()){
                    sum*=ops.pop();
                }
                nums.push(sum);
            }
        }
        if (num!=0){
            nums.push(sign*num);
        }
        int res=0;
        while (!nums.isEmpty()){
            res+=nums.pop();
        }
        return res;
    }
}
